package com.mingqijia.gassafety.job.job.message;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.db.entity.AppealLog;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.ConsumerDtuHistory;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.entity.HistoryAlarm;
import com.mingqijia.gassafety.db.entity.RunningReport;
import com.mingqijia.gassafety.db.entity.RunningReportConfig;
import com.mingqijia.gassafety.db.entity.vo.HistoryAlarmVo;
import com.mingqijia.gassafety.db.mapper.AppealLogMapper;
import com.mingqijia.gassafety.db.mapper.ConsumerDtuHistoryMapper;
import com.mingqijia.gassafety.db.mapper.ConsumerMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.db.mapper.HistoryAlarmMapper;
import com.mingqijia.gassafety.db.mapper.HistoryBrokenMapper;
import com.mingqijia.gassafety.db.mapper.RunningReportConfigMapper;
import com.mingqijia.gassafety.db.mapper.RunningReportMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.enums.YesNoEnum;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.mingqijia.gassafety.shared.constant.Constants.IS_DELETED_FALSE;

/**
 * @author mby
 * @version 1.0.0
 * @ClassName CreateServiceInfoHistoryJob.java
 * @Description TODO
 * @createTime 2024年01月16日
 */
@Component
@Slf4j
public class RepairRunningReportJob {

    @Autowired
    RedisCacheExt redisUtil;
    @Autowired
    HistoryAlarmMapper historyAlarmMapper;
    @Autowired
    HistoryBrokenMapper historyBrokenMapper;
    @Autowired
    AppealLogMapper appealLogMapper;
    @Autowired
    DtuMapper dtuMapper;
    @Autowired
    RunningReportConfigMapper runningReportConfigMapper;
    @Autowired
    RunningReportMapper runningReportMapper;
    @Autowired
    ConsumerDtuHistoryMapper consumerDtuHistoryMapper;
    @Autowired
    ConsumerMapper consumerMapper;

    public static final Integer pageSize = 100;

    /**
     *   修复数据，执行一次后删除
     */
    @XxlJob("repairRunningDataJob")
    public ReturnT<String> repairRunningDataJob(String param) {
        XxlJobLogger.log("XXLJOB-repairRunningDataJob start..." );
        log.info("repairRunningDataJob--start--------");
        String key = Constants.EQUIPMENT_CREATE_SERVICE_INFO;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                try {
                    execute();
                    execute2();
                    execute3();
                    execute4();
                    return ReturnT.SUCCESS;
                } catch (Exception e) {
                    log.info("repairRunningDataJob-error:{}", e);
                } finally {
                    redisUtil.del(key);
                }
            }
        } catch (Exception e) {
            log.info("repairRunningDataJob-error:{}", e);
        }
        log.info("repairRunningDataJob--end--------");
        XxlJobLogger.log("XXLJOB-repairRunningDataJob end..." );
        return ReturnT.SUCCESS;
    }

    // 修复设备运行报告模版的某些自定义列表
    private boolean execute() {
        // 修复设备运行报告模版的某些自定义列表
        LambdaQueryWrapper<RunningReportConfig> queryWrapper = new LambdaQueryWrapper<>();

        List<RunningReportConfig> runningReportConfigList = runningReportConfigMapper.selectList(queryWrapper);
        for (RunningReportConfig runningReportConfig : runningReportConfigList) {
            log.info("repairRunningDataJob-runningReportConfig:{}", JSONObject.toJSONString(runningReportConfig));
            runningReportConfig.setAlarmSummaryListShow(runningReportConfig.getAlarmSummaryListShow()
                    .replace("时间","事件时间").replace("报警类别","事件").replace("报警原因","事件原因"));
            runningReportConfig.setAlarmDetailListShow(runningReportConfig.getAlarmDetailListShow()
                    .replace("报警地点","地点").replace("报警类别","事件").replace("报警时间","事件时间")
                    .replace("报警时气体浓度","事件记录").replace("报警原因","事件原因"));
            log.info("repairRunningDataJob-runningReportConfig2:{}", JSONObject.toJSONString(runningReportConfig));
            runningReportConfigMapper.updateById(runningReportConfig);
        }

        return true;
    }

    // 修复设备运行报告历史明细的有报警，有故障
    private boolean execute2() {
        int pageIndex = 1;
        long total = 0;
        do{
            Page<RunningReport> pages = PageHelper.startPage(pageIndex, pageSize);
            LambdaQueryWrapper<RunningReport> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RunningReport::getIsDeleted, IS_DELETED_FALSE)
                .eq(RunningReport::getReportContentType, "0"); // 有报警
            List<RunningReport> list = runningReportMapper.selectList(queryWrapper);
            pageIndex++;
            total = pages.getTotal();
            log.info("repairRunningDataJob-runningReport,{},{}", pages.getPages(), pages.getPageSize(), pages.getTotal());
            if (CollectionUtils.isNotEmpty(list)) {
                for (RunningReport x : list) {
                    boolean haveAlarm = false;
                    boolean haveBroken = false;
                    if (x.getAlarmProcessed() > 0 || x.getAlarmProcessing() > 0 || x.getAlarmPending() > 0) {
                        haveAlarm = true;
                    }
                    if (x.getBrokenProcessed() > 0 || x.getBrokenProcessing() > 0|| x.getBrokenPending() > 0) {
                        haveBroken = true;
                    }
                    if (haveAlarm && !haveBroken) {
                        // 有报警，不变
                        continue;
                    }
                    if (haveAlarm && haveBroken) {
                        x.setReportContentType("0,2");
                    }
                    if (!haveAlarm && haveBroken) {
                        x.setReportContentType("2");
                    }
                    runningReportMapper.updateById(x);
                }
            }
            list.clear();
        }while(total > (pageIndex - 1) * pageSize);
        return true;
    }

    // 刷历史数据的行业类型
    private boolean execute3() {
        // 查询所有有客户id的设备
        QueryWrapper<RunningReport> runningReportQueryWrapper = new QueryWrapper<>();
        runningReportQueryWrapper.lambda()
                .eq(RunningReport::getIsDeleted,0);

        int pageIndex = 1;
        long total = 0;
        do {
            Page<RunningReport> pages = PageHelper.startPage(pageIndex, pageSize);
            List<RunningReport> runningReportList = runningReportMapper.selectList(runningReportQueryWrapper);
            pageIndex++;
            total = pages.getTotal();
            if (!CollectionUtils.isEmpty(runningReportList)) {
                runningReportList.stream().forEach(runningReport -> {
                    if (runningReport.getConsumerId() != null && runningReport.getConsumerId() > 0 ) {
                        Consumer consumer = consumerMapper.selectById(runningReport.getConsumerId());
                        if (consumer != null) {
                            runningReport.setIndustryType(StringUtils.isBlank(consumer.getIndustryType()) ? Constants.BLANK : consumer.getIndustryType());
                            runningReportMapper.updateById(runningReport);
                        }
                    }

                });
            }

        }while(total > (pageIndex - 1) * pageSize);

        return true;
    }

    // 删除没有设备的客户的运行报告
    private boolean execute4() {
        // 查询所有有客户id的设备
        RunningReport runningReport = new RunningReport();
        runningReport.setIsDeleted(YesNoEnum.Y.isFlag());
        QueryWrapper<RunningReport> runningReportQueryWrapper = new QueryWrapper<>();
        runningReportQueryWrapper.lambda()
            .eq(RunningReport::getDeviceType, Constants.BLANK)
            .eq(RunningReport::getIsDeleted, Constants.IS_DELETED_FALSE);
        runningReportMapper.update(runningReport, runningReportQueryWrapper);

        return true;
    }

}